/**
 * 
 */
package gwtool.gui.components;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * @author Christian
 * 
 */
public class JTextAreaWithMenu extends JTextArea implements ActionListener, ChangeSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4245684747536984380L;

	/** */
	private final JPopupMenu cutpasteMenu = new JPopupMenu();

	/** */
	private JMenuItem cutMenuItem = new JMenuItem("Ausschneiden");

	/** */
	private JMenuItem copyMenuItem = new JMenuItem("Kopieren");

	/** */
	private JMenuItem pasteMenuItem = new JMenuItem("Einfügen");

	private String alterInhalt = "";

	/**
	 * 
	 */
	public JTextAreaWithMenu() {

		super();
		initMenu();
	}

	public JTextAreaWithMenu(String s) {

		super(s);
		initMenu();
	}

	@Override
	public void setText(String t) {

		alterInhalt = t;
		super.setText(t);
	}

	@Override
	public boolean hasChanged() {

		return !getText().equals(alterInhalt);
	}

	/** */
	private void initMenu() {

		cutMenuItem.addActionListener(this);
		copyMenuItem.addActionListener(this);
		pasteMenuItem.addActionListener(this);
		cutpasteMenu.add(cutMenuItem);
		cutpasteMenu.add(copyMenuItem);
		cutpasteMenu.add(pasteMenuItem);
		this.addMouseListener(new MouseAdapter() {

			@Override
			public void mousePressed(MouseEvent e) {

				switch (e.getModifiers()) {
				case InputEvent.BUTTON3_MASK:
					cutpasteMenu.show(e.getComponent(), e.getX(), e.getY());
					break;
				default:
				}
			}
		});
	}

	/**
	 * 
	 * 
	 * @author Christian
	 * @since 5.0.8
	 * @param evt
	 *            Action
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent evt) {

		Object source = evt.getSource();
		if (source == cutMenuItem) {
			JTextField jte = (JTextField) cutpasteMenu.getInvoker();
			jte.cut();
		}
		if (source == copyMenuItem) {
			JTextField jte = (JTextField) cutpasteMenu.getInvoker();
			jte.copy();
		}
		if (source == pasteMenuItem) {
			JTextField jte = (JTextField) cutpasteMenu.getInvoker();
			jte.paste();
		}
	}

	@Override
	public void setChangedFalse() {

		alterInhalt = getText();
	}
}
